package com.xufx.thread.liaoxuefeng.thread7_deadLock;

public class DeadLockTask implements Runnable {
    private Object lock1;
    private Object lock2;
    private Boolean flag;


    public DeadLockTask(Object o1, Object o2, Boolean flag) {
        this.lock1 = o1;
        this.lock2 = o2;
        this.flag = flag;
    }

    @Override
    public void run() {

        synchronized (lock1) {
            if (flag) {
                System.out.println(Thread.currentThread().getName() + "---- Xixi：holding orange...");

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


                System.out.println(Thread.currentThread().getName() + "---- Xixi: waiting for lock of Hoho");
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + "---- Xixi: got Hoho's lock: apple");
                }
            }
        }

        if (!flag) {
            System.out.println(Thread.currentThread().getName() + "---- Hoho：holding apple...");

            synchronized (lock2) {

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + "---- Hoho: waiting for lock of Xixi");
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + "---- Hoho: got Xixi's lock: orange");
                }
            }

        }

    }
}
